package hot100.logos21To30;

import hot100.datastruct.ListNode;

/**
 * @author logos
 * date 2025/7/12 10:56
 * @version v1.0
 * @Package hot100
 */
public class logos22 {

    /**
     * 22. 相交链表
     * https://leetcode.cn/problems/intersection-of-two-linked-lists/?envType=study-plan-v2&envId=top-100-liked
     */

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode a = headA;
        ListNode b = headB;
        int diff = 0;
        while (a != null) {
            a = a.next;
            diff++;
        }
        while (b != null) {
            b = b.next;
            diff--;
        }
        if (diff > 0) {
            a = headA;
            b = headB;
        } else {
            diff = -diff;
            a = headB;
            b = headA;
        }
        while (diff > 0) {
            a = a.next;
            diff--;
        }
        while (a != b) {
            a = a.next;
            b = b.next;
        }
        return a;
    }
}
